package com.fantabest.importers;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.Transaction;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import com.fantabest.common.PMF;
import com.fantabest.common.entity.Player;
import com.fantabest.common.entity.Season;
import com.fantabest.common.server.dao.PlayerDao;
import com.fantabest.common.server.dao.SeasonDao;

public class GazzettaImporter {

	private static GazzettaImporter instace;

	public static GazzettaImporter getInstace() {
		if (instace == null)
			instace = new GazzettaImporter();
		return instace;
	}

	public int importPlayers(String fileName, int startRow, Long seasonId)
			throws BiffException, IOException {
		Workbook workbook = Workbook.getWorkbook(new File(fileName));
		return doImport(workbook, startRow,seasonId);
	}

	public int importPlayers(InputStream inputStream, int startRow, Long seasonId)
			throws BiffException, IOException {
		int result = 0;
		Transaction tx = PMF.get().getPersistenceManager().currentTransaction();
		tx.begin();

		PlayerDao.getInstance().deleteAll();
		Workbook workbook = Workbook.getWorkbook(inputStream);
		result = doImport(workbook, startRow,seasonId);
		
		tx.commit();
		
		if (tx.isActive()) {
			tx.rollback();
		}

		return result;
	}

	private int doImport(Workbook workbook, int startRow, Long seasonId) {
		Sheet sheet = workbook.getSheet(0);

		int recordInserted = 0;
		List<Player> playersList = new ArrayList<Player>();
		Season season = SeasonDao.getInstance().getSeasonById(seasonId);
		for (int i = startRow - 1; i < sheet.getRows(); i++) {
			Cell[] row = sheet.getRow(i);

//			Key key = KeyFactory.createKey(Player.class.getSimpleName(), (Long.parseLong(row[0].getContents())));
			Player player = new Player();
			player.setId(Long.parseLong(row[0].getContents()));
			player.setPosition(row[1].getContents());
			player.setLastname(row[2].getContents());
			player.setQuotation(Integer.parseInt(row[3].getContents()));
			player.setClub(row[4].getContents());
//			player.setSeason(season);
			
			playersList.add(player);
			
			recordInserted++;
		}
		PlayerDao.getInstance().save(playersList,seasonId);		
		return recordInserted;
	}

}
